<template>
  <div class="ask-leave-info">
    <group class="none-bottom-border">
      <cell-box class="cellbox-item">
        <flexbox>
          <flexbox-item class="title" :span="4">
            请假开始日期<span class="require-item">*</span>
          </flexbox-item>
          <flexbox-item class="value date-pciker" :span="8">
            <datetime v-model="startDate"
            :start-date="datePickerConfig.startDateConfig.startDate"
            :end-date="datePickerConfig.startDateConfig.endDate"
            placeholder="请选择请假开始日期" :format="datePickerConfig.format"
            :min-hour="datePickerConfig.workStartHour"
            :max-hour="datePickerConfig.workEndHour"
            :minuteList="datePickerConfig.startDateConfig.minuteList"
            @on-change="dateChange('startDate')"
            ref="startDateDom"
            clear-text="请选择请假开始日期" class="datetime"></datetime>
          </flexbox-item>
        </flexbox>
      </cell-box>
      <cell-box class="cellbox-item">
        <flexbox>
          <flexbox-item class="title" :span="4">
            请假结束日期<span class="require-item">*</span>
          </flexbox-item>
          <flexbox-item class="value date-pciker" :span="8">
            <datetime v-model="endDate"
            :start-date="datePickerConfig.endDateConfig.startDate"
            placeholder="请选择请假结束日期" :format="datePickerConfig.format"
            :max-hour="datePickerConfig.workEndHour"
            :min-hour="datePickerConfig.workStartHour"
            :minuteList="datePickerConfig.endDateConfig.minuteList"
            @on-change="dateChange('endDate')"
            ref="endDateDom"
            clear-text="请假结束日期" class="datetime"></datetime>
          </flexbox-item>
        </flexbox>
      </cell-box>
      <cell-box class="cellbox-item">
        <flexbox>
          <flexbox-item class="title" :span="4">
            请假小时数<span class="require-item">*</span>
          </flexbox-item>
          <flexbox-item class="value leave-minute" :span="8">
            <input type="tel" v-model="applyTimeText"
            placeholder="请输入小时数（共_天）" readonly>
            <input type="hidden" v-model="applyMinute" >
          </flexbox-item>
        </flexbox>
      </cell-box>
      <cell-box class="cellbox-item">
        <flexbox>
          <flexbox-item class="title" :span="4">
            请假原因<span class="require-item">*</span>
          </flexbox-item>
          <flexbox-item class="value" :span="8">
            <x-textarea class="apply-reason" v-model="reasonText" :placeholder="'请输入请假原因'"></x-textarea>
          </flexbox-item>
        </flexbox>
      </cell-box>
      <cell-box class="cellbox-item" v-if="changeApplyType === '修改申请原因'">
        <flexbox>
          <flexbox-item class="title" :span="4">
            修改申请原因<span class="require-item">*</span>
          </flexbox-item>
          <flexbox-item class="value" :span="8">
            <x-textarea class="apply-reason" v-model="editApplyReason" :placeholder="'请输入修改申请原因'"></x-textarea>
          </flexbox-item>
        </flexbox>
      </cell-box>
      <cell-box class="cellbox-item" v-if="changeApplyType === '重新申请原因'">
        <flexbox>
          <flexbox-item class="title" :span="4">
            重新申请原因<span class="require-item">*</span>
          </flexbox-item>
          <flexbox-item class="value" :span="8">
            <x-textarea class="apply-reason" v-model="reApplyReason" :placeholder="'请输入重新申请原因'"></x-textarea>
          </flexbox-item>
        </flexbox>
      </cell-box>
      <cell-box class="cellbox-item">
        <flexbox>
          <flexbox-item class="title" :span="4">
            请假类型<span class="require-item">*</span>
          </flexbox-item>
          <flexbox-item class="value leave-type" :span="8">
            <label v-for="(item,index) in applyTypeArr" :key="index" :for="`radio${index}`">
              <template v-if="item.ItemCode !== '其他'">
                <input type="radio" :id="`radio${index}`" class="apply-radio" :value="item.KeyId"
                v-model="applyType" @change="applyTypeChange(item)" />
                {{item.ItemCode}}
              </template>
              <template v-else>
                <input type="radio" :id="`radio${index}`" class="apply-radio" :value="item.KeyId"
                v-model="applyType" @change="applyTypeChange(item)" />
                {{item.ItemCode}}
                <input type="text" v-model="otherTypeReason"
                  class="other-type" id="other-type"
                  :placeholder="otherInputPlaceholder"
                  :disabled="otherTypeDisabled">
              </template>
            </label>
            <div v-if="!otherTypeDisabled" style="color:#999;">{{this.uploadContentReminder}}</div>
            <flexbox class="select-images-list" wrap="wrap">
              <flexbox-item v-for="(item, index) in imagesList" :key="index">
                <i class="remove-icon" @click="removePerson(index)"></i>
                <div class="img-box">
                  <img :src="item" @click="ImagesShow(index)">
                </div>
              </flexbox-item>
              <flexbox-item class="select-img" v-show="imagesList.length < 9">
                <input type="file" @change="getFileUrl()" ref="inputDOM" multiple accept="image/*">
              </flexbox-item>
            </flexbox>
          </flexbox-item>
        </flexbox>
      </cell-box>
    </group>
    <toast v-model="toastShow" :text="toastText" type="text" class="toast-normal" :time="3000"></toast>
    <!-- 圖片放大 -->
    <previewer :list="previewerImagesList" ref="previewer"></previewer>
  </div>
</template>

<script>
  import { Group, CellBox, Flexbox, FlexboxItem, XTextarea, Datetime, Toast, Previewer, dateFormat } from 'vux';
  import { Queue } from '@/assets/js/classLibrary.js';
  import qs from 'qs';
  import { getMinutes } from '@/assets/js/computedMinutes.js';
  export default {
    name: 'AskLeaveInfo',
    data () {
      return {
        startDate: '',
        endDate: '',
        datePickerConfig: {
          format: 'YYYY-MM-DD HH:mm', // 日期格式
          workEndHour: 18, // 下班時間
          workStartHour: 9, // 上班時間
          startDateConfig: {
            startDate: '',
            endDate: '',
            minuteList: ['00', '15', '30', '45']
          },
          endDateConfig: {
            startDate: '',
            endDate: '',
            minuteList: ['00', '15', '30', '45']
          }
        },
        applyTimeText: '', // 請假分鐘+天數 顯示
        applyDay: '', // 請假天数【提交】
        applyMinute: '',   // 請假分鐘【提交】
        reasonText: '',   // 請假原因，【提交】
        applyTypeArr: [], // 請假類型數組
        applyType: '',    // 請假類型KeyId，【提交】
        applyTypeCode: '',     // 請假類型中文，用於判斷
        otherTypeReason: '',    // 其他類型原因 【提交】
        otherInputPlaceholder: '', // 其他類型文本框提示
        otherTypeDisabled: true,  // 其他類型文本框是否禁用
        workHours: 0,
        uploadQueue: new Queue(), // 圖片上傳隊列
        imagesList: [],         // 用於顯示的圖片數組【提交】
        imagesUploadList: [],   // 用於上傳的圖片數組，不包含'data:image/jpeg;base64'的開頭
        previewerImagesList: [], // Previewer組件所需格式
        toastShow: false,       // 是否顯示提示框
        toastText: '',           // 提示框文字
        reApplyReasonShow: false,
        reApplyReason: '',      // 重新申請原因
        editApplyReason: '',    // 修改申請原因
        changeApplyType: '',
        uploadContentReminder:'' //上传内容提示
      };
    },
    components: {
      Group,
      CellBox,
      Flexbox,
      FlexboxItem,
      XTextarea,
      Datetime,
      Toast,
      Previewer
    },
    watch:{
      otherTypeReason(val, oldVal){
        var str = val.trim()
        if(str === "产假" || str === "陪产假"){
          this.uploadContentReminder = "要提交夫妻双方身份证，结婚证，准生证，宝宝手册登记页"
        }else if(str === "产检假"|| str === "产检"){
          this.uploadContentReminder = "需要提供宝宝手册登记页"
        }else if(str === "婚假"){
          this.uploadContentReminder = "需要夫妻双份身份证，结婚证"
        }else if(str === "节育假"){
          this.uploadContentReminder = "需要提供宝宝出生证明，节育证明"
        }else if(str === "丧假"){
          this.uploadContentReminder = "需要关系证明，死亡证明"
        }else{
          this.uploadContentReminder = ''
        }
      }
    },
    mounted () {
      this.applyTypeArr = this.getTypeKeyValue();
      // this.applyTypeArr = [];
      this.datePickerInit();
      let userInfo = this.getUserInfo();
      if (userInfo.IsBusiness !== undefined) {
        this.workHours = userInfo.IsBusiness === 'S' ? 6.67 : 8;
        // this.workHours = 6.67
        userInfo = null;
      }
      // this.otherInputBlur(); // 解决移动端键盘弹出影响body高度问题
    },
    methods: {
      datePickerInit: function () {
        this.datePickerConfig.startDateConfig.endDate = this.formatDateToYYYYMMDD(this.endDate);
        this.datePickerConfig.endDateConfig.startDate = this.formatDateToYYYYMMDD(this.startDate);
      },
      // 更改請假類型
      applyTypeChange: function (item) {
        let res = null;
        this.applyTypeCode = item.ItemCode;
        this.datePickerConfig.startDateConfig.startDate = '';
        this.datePickerConfig.endDateConfig.startDate = this.formatDateToYYYYMMDD(this.startDate);
        if (item.ItemCode === '其他') {
          this.otherTypeDisabled = false;
          this.otherInputPlaceholder = '其他原因（必填项）';
          this.$parent.required.push('Other');
          return false;
        } else if (this.applyTypeCode === '事假NPL（必须3日前完成审批）' || this.applyTypeCode === '加班补休OTL（必須3日前完成审批）') {
          res = this.checkDateAdvance(this.startDate, this.endDate, 3);
        } else if (this.applyTypeCode === '大假AL（必须15日前完成审批）') {
          res = this.checkDateAdvance(this.startDate, this.endDate, 15);
        }
        if (res !== null && res.status === false) {
          this.$parent.turndownText = res.message;
          this.$parent.turndownShow = true;
          // this.startDate = '';
          // this.$refs.startDateDom.currentValue = this.startDate;
          // this.endDate = '';
          // this.$refs.endDateDom.currentValue = this.endDate;
          // this.applyTimeText = '';
          // this.datePickerConfig.startDateConfig.startDate = this.formatDateToYYYYMMDD(res.advanceDateTimeStamp);
          // this.datePickerConfig.endDateConfig.startDate = this.datePickerConfig.startDateConfig.startDate;
        } else if (res !== null && res.status === true) {
          // this.datePickerConfig.startDateConfig.startDate = this.formatDateToYYYYMMDD(res.advanceDateTimeStamp);
          this.datePickerConfig.endDateConfig.startDate = this.formatDateToYYYYMMDD(res.advanceDateTimeStamp);
        }
        let requireArr = this.$parent.required;
        let otherIndex = null;
        requireArr.filter((item, index) => {
          if (item === 'Other') {
            otherIndex = index;
          }
        });
        if (otherIndex !== null) {
          this.$parent.required.splice(otherIndex, 1);
        }
        this.clearOhterTypeInput();
      },
      removePerson: function (index) {
        this.imagesList.splice(index, 1);
        this.imagesUploadList.splice(index, 1);
        this.previewerImagesList.splice(index, 1);
      },
      // 解决移动端键盘弹出影响body高度问题
      otherInputBlur: function () {
        let otherInputDOM = document.querySelector('#other-type');
        otherInputDOM.addEventListener('blur', function () {
          window.scroll(0, 0);
        });
      },
      // 请假分钟失焦自动计算请假天数
      computeDays: function () {
        let applyTimeNumber = parseInt(this.applyTimeText);
        // let startDay = new Date(this.startDate.replace(/-/g, '/') + ':00').getDate();
        // let endDay = new Date(this.endDate.replace(/-/g, '/') + ':00').getDate();
        if (this.applyTimeText === '') {
          return false;
        }
        if (applyTimeNumber > 85440) {
          alert('请假不能超过178天');
          this.applyTimeText = '';
          this.applyMinute = '';
          return false;
        } else if (applyTimeNumber < 0) {
        //   alert('請假分鐘數不能少於0分鐘');
          this.applyTimeText = '';
          this.applyMinute = '';
          return false;
        }
        this.applyMinute = this.applyTimeText;
        this.applyDay = (this.applyMinute / (this.workHours * 60)).toFixed(2);
        // if (endDay - startDay === 0 && this.applyDay > 1) {
        //   this.applyDay = 1;
        // }
        this.applyTimeText = `${(this.applyMinute/60).toFixed(2)}小时（共${this.applyDay}天）`;
      },
      // 获取焦点清空请假分钟
      // clearApplyMinute: function () {
      //   this.applyTimeText = '';
      //   this.applyMinute = '';
      //   this.applyDay = '';
      // },
      ImagesShow: function (index) {
        this.$refs.previewer.show(index);
      },
      getFileUrl: function (e) {
        // input file element
        let inputEl = this.$refs.inputDOM;
        let filesArr = inputEl.files;
        let oldFileLength = this.imagesList.length;
        let newFileLength = inputEl.files.length + oldFileLength;
        // 限制圖片數量
        if (newFileLength > 9) {
          this.toastShow = true;
          this.toastText = '你只能上传9张图片';
          return false;
        }
        // 遍歷讀取圖片
        for (let i = 0; i < filesArr.length; i++) {
          // 限制圖片大小
          // let size = filesArr[i].size / 1024;
          // if (size > 2 * 1024) {
          //   this.toastShow = true;
          //   this.toastText = '單張圖片大小不能超過2M';
          //   return false;
          // }
          let reader = new FileReader();
          let _this = this;
          reader.onload = function () {
            let result = reader.result;
            let base64Header = result.slice(0, result.indexOf(',') + 1);
            let base64UploadUrl = result.replace(base64Header, '');
            if (!_this.isImageFormat(base64Header)) {
              alert('只允许上传图片格式文件');
              return false;
            }
            // _this.imagesUploadList.push(base64UploadUrl);
            // _this.uploadQueue.enqueue(base64UploadUrl);
            _this.imagesUploadList.push(filesArr[i]);
            _this.uploadQueue.enqueue(filesArr[i]);
            // 全部加入隊列后執行上傳
            if (i === filesArr.length - 1) {
              _this.$parent.loadingShow = true;
              _this.uploadFile();
              inputEl.value = '';
            }
          };
          reader.readAsDataURL(filesArr[i]);
        }
      },
      uploadFile: function () {
        this.$parent.loadingShow = true;
        if (!this.uploadQueue.empty()) {
          // let postData = {
          //   data: {
          //     Image: this.uploadQueue.getFirst()
          //   }
          // };
          let file = this.uploadQueue.getFirst()
          let param = new FormData();
          param.append("name", file.name);
          param.append("file", file);
          // this.axios.post('/Process/FileUpdate', qs.stringify(postData))
          this.axios.post('/Process/FileUpdate', param,{ headers: { "Content-Type": "multipart/form-data"},})
          .then((res) => {
            this.$parent.loadingShow = false;
            if (res.data.IsScuess === 0) {
              // this.imagesList.push(res.data.data.Filepath);
              let [Filepath] = [...res.data.Filepath]
              this.imagesList.push(Filepath)
              // this.previewerImagesList.push({src: res.data.data.ImagePath});
              this.previewerImagesList.push({src: Filepath});
              this.uploadQueue.dequeue();
              this.uploadFile();
            } else {
              this.toastShow = true;
              this.toastText = `上传图片时发生错误，错误信息：${res.data.ExMessage}`;
              this.imagesUploadList = [];
              this.uploadQueue.clear();
            }
          })
          .catch((err) => {
            this.$parent.loadingShow = false;
            this.toastShow = true;
            this.toastText = `上传图片时发生错误，错误信息：${err}`;
            this.imagesUploadList = [];
            this.uploadQueue.clear();
          });
        } else {
          this.$parent.loadingShow = false;
        }
      },
      inputMinute: function () {
        if (this.applyTimeText && (/[^0-9]/).test(this.applyTimeText)) {
          let newStr = this.applyTimeText.replace(/[^0-9]/g, '');
          this.applyTimeText = newStr;
        }
      },
      isImageFormat: function (url) {
        if (url.indexOf('image') === -1) {
          return false;
        }
        return true;
      },
      // 日期更改時的回調
      dateChange: function (dateType) {
        let startDate = this.formatDateToYYYYMMDD(this.startDate);
        let endDate = this.formatDateToYYYYMMDD(this.endDate);
        if (endDate) {
          this.datePickerConfig.startDateConfig.endDate = endDate;
        } else {
          this.datePickerConfig.startDateConfig.endDate = '';
        }
        if (startDate) {
          this.datePickerConfig.endDateConfig.startDate = startDate;
        }
        if (startDate && endDate) {
          this.applyTimeText = getMinutes(this.startDate, this.endDate, this.getUserInfo().IsBusiness);
          this.computeDays();
        }
        this.checkDateRange();
      },
      formatDateToYYYYMMDD: function (date) {
        if (!date) return;
        return dateFormat(date, 'YYYY-MM-DD');
      },
      // 檢查請假開始日期是否大於請假結束日期
      checkDateRange: function () {
        let startDate = new Date(this.startDate.replace(/ /g, 'T'));
        let endDate = new Date(this.endDate.replace(/ /g, 'T'));
        if (startDate > endDate) {
          this.endDate = '';
          this.$refs.endDateDom.currentValue = this.endDate;
          this.$parent.turndownText = '请假开始日期不能大于请假结束日期';
          this.$parent.turndownShow = true;
        }
      },
      // 檢查日期是否符合請假類型要求提前的天數
      checkDateAdvance: function (startDateStr, endDateStr, AdvanceDays) {
        let todayDate = new Date();
        todayDate.setHours(0);
        todayDate.setMinutes(0);
        todayDate.setSeconds(0);
        let advanceDateTimeStamp = new Date(todayDate.getTime() + AdvanceDays * 86400000);
        if (startDateStr !== '') {
          let startDate = new Date(startDateStr.replace(/ /g, 'T'));
          if (startDate.getTime() <= advanceDateTimeStamp) {
            return {
              errorDate: 'startDate',
              advanceDateTimeStamp: advanceDateTimeStamp,
              message: `必须提前${AdvanceDays}天申请，请假开始或结束日期不符合要求`,
              status: false
            };
          }
        }
        if (endDateStr !== '') {
          let endDate = new Date(endDateStr.replace(/ /g, 'T'));
          if (endDate.getTime() <= advanceDateTimeStamp) {
            return {
              errorDate: 'endDate',
              advanceDateTimeStamp: advanceDateTimeStamp,
              message: `请假结束日期必须提前${AdvanceDays}天`,
              status: false
            };
          }
        }
        return {
          advanceDateTimeStamp: advanceDateTimeStamp,
          status: true
        };
      },
      clearOhterTypeInput: function () {
        // 設置‘其他’文本框禁選并清除內容
        this.otherTypeDisabled = true;
        this.otherInputPlaceholder = '';
        this.otherTypeReason = '';
        // 清除‘其他’文本框檢查
        let otherIndex = this.$parent.required.indexOf('Other');
        if (otherIndex >= 0) {
          this.$parent.required.splice(otherIndex, 1);
        }
      }
    }
  };
</script>

<style lang="scss" scoped>
  @import '../../assets/style/variable';
  .cellbox-item{
    padding: 0 15px;
    &:before{
      border-color: #e6e6e6;
    }
    .title{
      color: #666;
      font-size: getRem(28);
      padding: getRem(32) 0;
    }
    .value{
      font-size: getRem(28);
    }
    .date-pciker{
      padding: getRem(32) 0;
      a{
        padding: getRem(32) 0;
        display: inline;
        // padding: 0;
        color: #ddd;
        &:before{
          content: none;
        }
      }
      .has-value{
        color: #333;
      }
      .separation-symbol{
        color: #666;
      }
    }
    .leave-minute{
      input{
        display: block;
        width: calc(100% - 15px);
        border: 0;
        padding: getRem(32) 0;
        line-height: getRem(38);
        // line-height: getRem(102);
        font-size: getRem(28);
        outline: none;
        &::placeholder{
          color: #ddd;
        }
      }
    }
    .apply-reason{
      padding: getRem(32) 0;
    }
    .leave-type{
      padding: getRem(32) 0 0;
      label{
        display: block;
        line-height: getRem(42);
        padding: 0 getRem(10) getRem(15) getRem(50);
        position: relative;
      }
      .other-type{
        display: inline-block;
        width: calc(100% - #{getRem(120)});
        border: 0;
        font-size: getRem(28);
        line-height: getRem(50);
        border-radius: 0;
        padding: 0 getRem(10);
        border-bottom: 1px solid #ddd;
        &:disabled{
          background: #fff;
        }
      }
      .apply-radio{
        position: absolute;
        left: 0;
        top: getRem(3);
        display: inline-block;
        appearance: none;
        -webkit-appearance: none;
        width: getRem(36);
        height: getRem(36);
        background: url(../../assets/images/radio-default.png) no-repeat center center;
        background-size: getRem(36) getRem(36);
        outline: 0;
        &:checked{
          background-image: url(../../assets/images/radio-selected.png);
        }
      }
    }
    .select-images-list{
      margin-top: getRem(34);
    }
  }
  .vux-flexbox{
    align-items: flex-start;
  }
</style>
